package com.gec.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gec.entity.ActiveUser;
import com.gec.entity.Employee;
import com.gec.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/")
    public String login() {
        //获取权限操作对象,利用这个对象来完成用户登录操作
        Subject subject = SecurityUtils.getSubject();

        //用户登录前需要先登出,清理缓存
        subject.logout();

        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String md5Password, Model model, HttpSession session, boolean rememberMe) {

        //获取权限操作对象,利用这个对象来完成用户登录操作
        Subject subject = SecurityUtils.getSubject();

        //判断用户是否认证(登录)过
        if (!subject.isAuthenticated()) {
            //没认证过就要登录

            //生成用户令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Password, rememberMe);

            //用户登录
            try {
                subject.login(token);


            } catch (UnknownAccountException e) {
                model.addAttribute("errorMsg", "登录失败,账户不存在");
                return "login";
            } catch (IncorrectCredentialsException e) {
                model.addAttribute("errorMsg", "登录失败,密码错误");
                return "login";
            } catch (AuthenticationException e) {
                model.addAttribute("errorMsg", "认证失败");
                return "login";
            }
        }
        ActiveUser activeUser = (ActiveUser) subject.getPrincipal();

        model.addAttribute("user", activeUser);
        session.setAttribute("activeUser", activeUser);

        return "index";
    }

    @RequestMapping("/welcome")
    public String welcomePage() {
        return "welcome";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        //用户登出
        subject.logout();
        System.out.println("用户登出");
        return "login";
    }
}

